/**
 * created by zhouli on 2019/1/9
 * Email li.zhou@huilianyi.com
 * 渲染 单个 权限的限制条件
 */
import React from 'react';
import {deepCopy, isEmptyObj, messages} from "share/common";
import {connect} from 'react-redux';
import configureStore from 'stores';
import {setPermissionData} from 'actions/permission-data';
import {Select, Tag, Icon, Button, Checkbox, message} from 'antd';
import PDService from 'containers/permission-setting/role-permission-setting/role-permission-detail/components/permission-data/permission-data.service';
import 'styles/permission-setting/role-permission-setting/role-permission-detail/components/permission-data/data-rule-info.scss';
import {
  conditionItemExample,
  conditionLimitStr,
} from 'containers/permission-setting/role-permission-setting/role-permission-detail/components/permission-data/data-rule-model';
import ConditionItem from 'containers/permission-setting/role-permission-setting/role-permission-detail/components/permission-data/rule-item/condition-item';

const Option = Select.Option;
let conditionForCancel = false;
let conditionEditing = false;

class DataRuleInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading:false
    };
  }

  componentWillMount() {

  }

  //点击编辑动作
  actionEdit = () => {
    let permissionData = deepCopy(this.props.permissionData);
    if (PDService.checkConditionIsEditing(permissionData)) {
      message.warning(messages('permission-setting.key20')/*正在编辑，请先保存，再添加条件*/);
      return;
    }
    conditionForCancel = deepCopy(this.props.condition);
    conditionEditing = this.props.condition;
    conditionEditing["isEditing"] = true;
    PDService.getPermissionData(conditionEditing, this.props.permissionData, true);
  };
  //点击取消动作
  actionCancel = () => {
    if (conditionForCancel) {
      //是编辑
      PDService.getPermissionData(conditionForCancel, this.props.permissionData, true);
      conditionForCancel = false;
    } else {
      //是新增的条件
      let permissionData = deepCopy(this.props.permissionData);
      permissionData.conditionViewDTOS.pop();
      configureStore.store.dispatch(setPermissionData(permissionData));
    }
  };
  //模块改变
  actionModuleOptionChange = (val) => {
    //0.如果是编辑已有条件，模块是不能变动的（这个在标签 disabled 控制）
    conditionEditing = this.props.condition;
    let conditionItem = deepCopy(conditionItemExample);
    conditionEditing["entityCode"] = val;
    //1.如果模块发生改变，下面的细项全部要删除
    conditionEditing['conditionDetails'] = [conditionItem];
    PDService.getPermissionData(conditionEditing, this.props.permissionData, true);
  };

  //保存条件
  saveCondition = () => {
    this.setState({
      loading: true
    })
    if (conditionEditing['conditionDetails'][0].id) {
      this.updateDataPermissionTableItemDetail(conditionEditing);
    } else {
      this.createDataPermissionTableItemDetail(conditionEditing);
    }
  };
  checkConditionDetails = (pureCondition) => {
    let conditions = pureCondition.conditionDetails;
    if (conditions.length > 0) {
      for (let i = 0, iLen = conditions.length; i < iLen; i++) {
        let conditionSub = conditions[i];
        if (conditionSub.subFieldName && conditionSub.subFieldValue) {
          let conditionVals = conditionSub.conditionValues;
          if (conditionVals.length > 0) {
            //全部不能为空
            for (let j = 0, jLen = conditionVals.length; j < jLen; j++) {
              let vals = conditionVals[j];
              if (!vals.description && !vals.conditionValue) {
                return false
              }
            }
            return true;
          } else {
            //没有条件规则 值
            return false
          }
        }
        //没有条件规则 子字段
        // return false
      }
    } else {
      //没有条件规则
      return false
    }
  };
  //新建组织权限详情
  createDataPermissionTableItemDetail = (pureCondition) => {
    if (!this.checkConditionDetails(pureCondition)) {
      this.setState({
        loading: false
      })
      message.warning(messages('permission-setting.key50')/*请检查条件细项是否填写完整*/);
      return;
    }
    let permissionData = deepCopy(this.props.permissionData);
    let params = deepCopy(pureCondition);
    params.dataPermissionId = permissionData.id;
    PDService.createDataPermissionTableItemDetail(params)
      .then((res) => {
        this.setState({
          loading: false
        })
        conditionEditing = res.data;
        //是编辑
        PDService.getPermissionData(conditionEditing, this.props.permissionData, true);
        conditionForCancel = false;
      })
      .catch(() => {
        this.setState({
          loading: false
        })
      })
  };
  //更新组织权限详情
  updateDataPermissionTableItemDetail = (pureCondition) => {
    let permissionData = deepCopy(this.props.permissionData);
    let params = deepCopy(pureCondition);
    params.dataPermissionId = permissionData.id;
    PDService.updateDataPermissionTableItemDetail(params)
      .then((res) => {
        this.setState({
          loading: false
        })
        conditionEditing = res.data;
        //是编辑
        PDService.getPermissionData(conditionEditing, this.props.permissionData, true);
        conditionForCancel = false;
      })
      .catch((err) => {
        this.setState({
          loading: false
        })
      })
  };
  //id获取组织权限详情
  getDataPermissionTableItemDetail = (dataPermissionId) => {
    let params = {
      "dataPermissionId": dataPermissionId,
    };
    PDService.getDataPermissionTableItemDetail(params)
      .then((response) => {
        if (response.data && response.data.conditionViewDTOS) {
          configureStore.store.dispatch(setPermissionData(response.data));
        } else {
          configureStore.store.dispatch(setPermissionData({}));
        }
      })
      .catch(err => {
        configureStore.store.dispatch(setPermissionData({}));
      })
  };
  deleteDataPermissionTableItemDetail = () => {
    this.setState({
      loading: true
    })
    const {condition, permissionData} = this.props;
    let params = {
      dataPermissionId: permissionData.id,
      seq: condition.sequence
    };
    PDService.deleteDataPermissionTableItemDetail(params)
      .then((res) => {
        this.setState({
          loading: false
        })
        this.getDataPermissionTableItemDetail(permissionData.id);
      })
      .catch((err) => {
        this.setState({
          loading: false
        })
      })
  };
  //渲染条件细项
  //要根据字段类型（CostCenter），来渲染，每一个字段类型，可能不一样
  renderConditionItem = (condition) => {
    return condition.conditionDetails.map((conditionItem, index) => {
      return (<div
        key={index}
      >
        <ConditionItem
          itemIndex={index}
          isShowAddItem={condition.conditionDetails.length - 1 === index}
          condition={condition}
          conditionItem={conditionItem}
          isEditing={condition.isEditing}/>
      </div>);
    })
  };
  //渲染模块
  renderModuleName = (condition) => {
    return (
      <div className='module-select-wrap'>
        {!(!condition.isEditing ||
          this.props.condition.conditionDetails[0].id) && <div className='module-select-title'>
          <span>{messages('permission-setting.key21')/*请选择模块*/}</span>
        </div>}
        <Select
          style={{width: '200'}}
          disabled={!condition.isEditing ||
          this.props.condition.conditionDetails[0].id}
          value={condition['entityCode']}
          placeholder={messages("common.please.select")}
          onChange={this.actionModuleOptionChange}
        >
          {conditionLimitStr.map(item => {
            return <Option value={item.moduleCode}>{item.moduleName}</Option>
          })}
        </Select>
      </div>
    )
  };

  //渲染操作按钮
  renderBtn = () => {
    return (
      <div>
        <Button type='primary'
                onClick={this.actionEdit}> {messages('common.edit')/*编辑*/}
        </Button>
        &nbsp;&nbsp;
        <Button type='danger'
                loading={this.state.loading}
                onClick={this.deleteDataPermissionTableItemDetail}> {messages('common.delete')/*删除*/}
        </Button>
      </div>
    )
  };
  //渲染操作按钮
  renderBtnEditing = () => {
    return (
      <div>
        <Button type='primary'
                loading={this.state.loading}
                onClick={this.saveCondition}> {messages('common.save')/*保存*/}
        </Button>
        &nbsp;&nbsp;
        <Button
          onClick={this.actionCancel}> {messages('common.cancel')/*取消*/}
        </Button>
      </div>
    )
  };
  //渲染标题
  renderTitle = (condition) => {
    return (
      <div className='title-wrap'>
        <div className='title-text f-left'>
          <span>{messages('permission-setting.key22')/*条件*/}</span>
          &nbsp;
          <span>{condition.sequence}</span>
        </div>
        <div className='title-btn f-left'>
          {condition.isEditing ? this.renderBtnEditing() : this.renderBtn()}
        </div>
        <div className='clear'/>
      </div>
    )
  };

  render() {
    const {condition} = this.props;
    return (
      <div className="data-rule-info">
        {this.renderTitle(condition)}
        {this.renderModuleName(condition)}
        {this.renderConditionItem(condition)}
      </div>
    )
  }
}

DataRuleInfo.propTypes = {
  condition: React.PropTypes.object.isRequired,// 单个条件对象
};

DataRuleInfo.defaultProps = {
  tenantMode: false,
};


function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    permissionData: state.permissionData.permissionData
  }
}

export default connect(mapStateToProps)(DataRuleInfo);


